package com.huoniu.commons.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils extends org.apache.commons.lang3.StringUtils {
    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};


    public static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin) {
        String resultString = null;

        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
        } catch (Exception ex) {

        }
        return resultString;
    }


    /**
     * 是否是邮箱
     *
     * @param str
     * @return
     */
    public static boolean isemail(String str) {

        String regex = "[a-zA-Z0-9_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";

        return match(regex, str);


    }

    /**
     * 整数字验证
     *
     * @param str
     * @return
     */
    public static boolean isDigital(String str) {

        try {
            Long.parseLong(str);
            return true;
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }

    }

    /**
     * 小数字验证
     *
     * @param str
     * @return
     */
    public static boolean isDouble(String str) {

        try {
            Double.parseDouble(str);
            return true;
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }

    }

    /**
     * 判断账号性质，字母，数字，下划线组合，不能以数字开头。
     *
     * @param accout
     * @return
     */
    public static boolean isAccount(String accout) {
        if (!StringUtils.notNullAndEmpty(accout)) return false;
        String start = accout.substring(0, 1);
        return !isDigital(start) && accout.matches("[A-Za-z0-9_]+");
    }

    /**
     * 数字和字母组合
     *
     * @return boolean
     * @Title:
     * @author zrh
     * @date 2017年8月16日
     */
    public static boolean isDigitalLetter(String accout) {
        if (accout == null) return false;
        return accout.matches("[A-Za-z0-9_]+");
    }

    /**
     * @param dd  要处理的double数据
     * @param wit 小数点后几位
     * @return
     */
    public static double getDoubles(double dd, int wit) {
        String wstr = "1";
        for (int i = 0; i < wit; i++) {
            wstr += "0";
        }
        wstr += ".0";
        double ww = Double.valueOf(wstr);
        long l1 = Math.round(dd * ww);   //四舍五入
        double ret = l1 / ww;               //注意：使用   100.0   而不是   100
        return ret;
    }

    /**
     * 手机验证
     *
     * @return
     */
    public static boolean isTel(String str) {
        String regex = "^((13[0-10])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        int start = str.indexOf("1");
        if (start == 0 && str.length() == 11) {
            try {
                Long l = Long.parseLong(str);
                return true;
            } catch (Exception e) {
                return false;
            }
        }

        return false;

    }

    /**
     * 是否为手机或者固话
     *
     * @param str
     * @return boolean
     * @Title:
     * @author zrh
     * @date 2017年5月26日
     */
    public static boolean isPhone(String str) {
//		  String regExp ="^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}|[0]{1}[0-9]{2,3}-[0-9]{7,8}$";
        String regExp = "^[0]{1}[0-9]{2,3}-[0-9]{7,8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.find();

    }

    /**
     * 判断字符串 非null 非空
     * s!=null && s.trim().length()>0
     *
     * @param s
     * @return
     */
    public static boolean notNullAndEmpty(String s) {
        if (s != null && s.trim().length() > 0) {
            return true;
        }
        return false;
    }


    /**
     * 通过 表id 生产16位随机数 aababab...aaaaa a代表随机数 b代表id
     *
     * @param tblid
     * @param perch
     * @return
     */
    public static String getSigleDigte(String tblid, int perch) {
        String rel10 = null;
        int idlen = tblid.length();
        int relstrlen = 2 * idlen + 1;//生产后的字符数量
        if (relstrlen > perch) {
            perch = relstrlen;
        }
        int rcount = idlen + 1;
        String random = getRandCode(1, rcount);
        char[] idchar = tblid.toCharArray();
        char[] rchar = random.toCharArray();
        StringBuffer sb = new StringBuffer();
        sb.append(rchar[0]);
        for (int i = 1; i < rcount; i++) {
            sb.append(rchar[i]);
            sb.append(idchar[i - 1]);
        }
        rel10 = sb.toString() + getRandCode(1, perch - rcount - idlen);
        return rel10;
    }

    /**
     * 返回一定长度的字符串 tblid 不够 前面补0
     *
     * @param tblid 要操作的字符串
     * @param perch 返回字符串的长度
     * @return
     */
    public static String getLenString(String tblid, int perch) {
        String fm = "%0" + perch + "d";
        String str2 = String.format(fm, Integer.valueOf(tblid));
        return str2;
    }

    /**
     * 获取随机 验证码 type=1 数字 2字母 3数字和字母组合
     * len 返回 位数。len<=0 则返回 4位
     *
     * @return
     */
    public static String getRandCode(int type, int length) {
        String soucrstr = "2345678qwertyupkhfdsazxcvbnm";
        int lens = length;
        if (type == 1) {
            soucrstr = "1234567890";
        } else if (type == 2) {
            soucrstr = "qwertyupkhfdsazxcvbnm";
        }
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        char[] ch = soucrstr.toCharArray();
        int index, len = ch.length;
        for (int i = 0; i < lens; i++) {
            index = r.nextInt(len);
            sb.append(ch[index]);
        }

        return sb.toString();
    }

    private static boolean match(String regex, String str) {

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(str);

        return matcher.matches();

    }

    /**
     * 去掉开头的分割符号
     *
     * @param sourcestr
     * @param split
     * @return
     */
    public static String removeFirstSplit(String sourcestr, String split) {
        if (sourcestr != null) {
            int frist = sourcestr.indexOf(split);
            int len = sourcestr.length();
            if (frist == 0) {
                sourcestr = sourcestr.substring(1, len);
            }
        }
        return sourcestr;
    }

    /**
     * 去掉 结尾的分隔符号
     *
     * @param sourcestr
     * @param split
     * @return
     * @author zhangrh
     * @version 2016-08-02
     */
    public static String removeLastSplit(String sourcestr, String split) {
        if (notNullAndEmpty(sourcestr)) {
            int last = sourcestr.lastIndexOf(split);
            int len = sourcestr.length();
            if (last == len - 1) {
                sourcestr = sourcestr.substring(0, len - 1);
            }
        }
        return sourcestr;
    }

    public static String getProperties(String key) {

        return Global.getConfig(key);
    }

    private static final String CHARSET_NAME = "UTF-8";

    /**
     * 转换为字节数组
     *
     * @param bytes
     * @return
     */
    public static String toString(byte[] bytes) {
        try {
            return new String(bytes, CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            return EMPTY;
        }
    }

    /**
     * 转换为字节数组
     *
     * @param str
     * @return
     */
    public static byte[] getBytes(String str) {
        if (str != null) {
            try {
                return str.getBytes(CHARSET_NAME);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        } else {
            return null;
        }
    }


    public static void main(String[] args) {
        System.err.println(MD5Encode("123456"));
//	    System.out.println(isPhone("053712345671"));

    }

    //	  public static final String LOGIN_NAME="login_name";
//	  public static final String LOGIN_PASSOWRD="login_password";
//	  public static final String LOGIN_NAME_TIP="手机号/会员名/邮箱";
    public static final String GET = "GET";//get访问
    public static final String POST = "POST";//post访问
    public static final String VERIFY_CODE = "verify_code";//验证码
    //	  public static final String DESPATCHRUL="DESPATCHRUL";//管理员
    public static final String LOGIN_USER = "login_user";//管理员登陆 对象
    //	  public static final String WEBROOT_FILE_ASSISTANT="assistant";
    public static final String MANNER_DETELE_DATA = "zhang";//删除数据权限的 账号名称
//	  public static final String WEIXIN_LOGIN_USER_CODE="WEIXIN_LOGIN_USER_CODE";//删除数据权限的 账号名称
    /**
     * 科目树 深度 5
     */
    public static final int CATALOG_LEVEL = 5;//
    /**
     * 知识点树 深度 2
     */
    public static final int KNOW_LEVEL = 2;//
    /**
     * 资讯类型 树 深度 6
     */
    public static final int NEWSTYPE_LEVEL = 6;//

    /**
     * 缓存 菜单列表
     */
    public static final String MENU_MAP = "menuMap";
    /**
     * 实际物理路径
     */
    public static final String FILE_REAL_PATH = "fileRealPath";
    /**
     * 访问url
     */
    public static final String FILE_WEB_URL = "fileWebUrl";
    /**
     * 防止并发 开关
     */
    public static boolean BING_FA_COLSE = true;
    /**
     * 数据库备份 路径
     */
//	  public static final String BAK_DATEBADE_PATH="bakdatabasepath";

    /**
     * 缓存文件路径，系统定时删除
     **/
    public static final String TEMP_FILE_PATH = "temp.file.path";
    /**
     * 数据库 备份 bat文件位置
     */
//	  public static final String BAK_DATEBADE_BATFILE="bakdatabasebatfile";
    /**
     * mysql 安装路径
     */
//	  public static final String BAK_MYSQL_PATH="mysqlpath";
    /**
     * MYSQL 信息
     */
//	  public static final String BAK_MYSQL_INFO="mysqlinfo";
    /**
     * 列表数据 查询异常返回标识
     */
    public static final int GET_TABLE_EORR = -99;
    //微信
//	  public static final String WEIXIN_appID="wx69ba073bd7f6f287";
//	  public static final String WEIXIN_appsecret="d4624c36b6795d1d99dcf0547af5443d";
//
//	  public static final String WEIXIN_appID="WEIXIN_appID";
//	  public static final String WEIXIN_appsecret="WEIXIN_appsecret";
//	  public static final String WEIXIN_LOGIN_USER_ID="weixin_login_user_id";
//	  public static final String WEIXIN_LOGIN_USER_NAME="weixin_login_user_name";
//	  public static final String WEIXIN_LOGIN_USER_CODE="weixin_login_user_code";
    /**
     * 微信公众号的id
     */
//	  public static final String WEIXIN_FROM_USER_ID="WEIXIN_FROM_USER_ID";
    /**
     * 系统微信用户 角色标示。
     * <br>使用：StrUtil.getProperties(StrUtil.WEIXIN_USER_TYPE)
     */
    public static final String WEIXIN_USER_TYPE = "WEIXIN_USER_TYPE";
    /**
     * 微信 告警模板id
     */
//	  public static final String WEIXIN_TEMPLATE_ID="WEIXIN_TEMPLATE_ID";
    /**
     * 注册表 表英文名前缀
     */
    public static final String DATAS_TB_QIANZHUI = "t_rw";
    /**
     * 元数据 采集 公共字段
     */
    public static final String DATAS_TB_CM_ITEMID = "itemId";
    public static final String DATAS_TB_CM_ID = "id";
    public static final String DATAS_TB_CM_INDATE = "cmIndate";
    public static final String DATAS_TB_CM_UPDATEDATE = "cmUpdateDate";
    public static final String DATAS_TB_CM_USERID = "cmUserId";
    public static final String DATAS_TB_CM_DELFLAG = "delFlag";


    public static final String DATAS_TB_CM_ITEMID_NAME = "ID";
    public static final String DATAS_TB_CM_INDATE_NAME = "数据入库时间";
    public static final String DATAS_TB_CM_UPDATEDATE_NAME = "数据更新时间";
    public static final String DATAS_TB_CM_USERID_NAME = "数据管理者";
    public static final String DATAS_TB_CM_DELFLAG_NAME = "逻辑删除";

    public static final String DATAS_TB_CM_TIME_FUN = "tb_list_time_fun";


    /**
     * 图片 真实路径和访问url
     */
    public static final String DATAS_TP_REAL_PATH = "cjFileRealPath";
    public static final String DATAS_TP_WEB_URL = "cjFileWebUrl";
    /**
     * 元数据 表单类型 文本框
     */
    public static final int DATAS_COL_TYPE_INPUT = 101101;
    /**
     * 单选下拉框
     */
    public static final int DATAS_COL_TYPE_SELECT_SIGLE = 101102;
    /**
     * 多选下拉框
     */
    public static final int DATAS_COL_TYPE_SELECT_MORE = 101103;
    /**
     * 联动下拉框
     */
    public static final int DATAS_COL_TYPE_SELECT_LD = 101104;
    public static final int DATAS_COL_TYPE_TUPIAN = 101105;
    public static final int DATAS_COL_TYPE_DATE = 101106;
    public static final int DATAS_COL_TYPE_AREA = 101107;
    public static final int DATAS_COL_TYPE_TREE = 101108;

    /**
     * 下拉框 区域 省
     */
    public static final int DATAS_COL_REGION_P = 101701;
    public static final int DATAS_COL_REGION_C = 101702;
    public static final int DATAS_COL_REGION_T = 101703;


    /**
     * id 前缀
     */
    public static final String DATAS_ID_PREFIX = "cj_c_";


    /**
     * 字典值
     */
    /**
     * 是否状态 是
     */
    public static final int DIC_ZT_SHI = 100901;
    /**
     * 是否状态 否
     */
    public static final int DIC_ZT_FOU = 100902;
    /**
     * 性别 男
     */
    public static final int DIC_SEX_MALE = 100901;
    /**
     * 性别女
     */
    public static final int DIC_SEX_FEMALE = 100902;


    /**
     * 表字段-公共字段1：公共字段 1 非公字段 0
     */
    public static final int DATAS_COL_COMM_YES = 1;
    /**
     * 表字段-非公共字段0：公共字段 1 非公字段 0
     */
    public static final int DATAS_COL_COMM_NO = 0;


    /**
     * 菜单编号 参数
     */
    public static final String MENU_CODE = "_m_c";
    /**
     * 初始化/未提交 0
     */
    public static final int VERIFY_STATUS_WTJ = 101901;
    /**
     * 审核中
     */
    public static final int VERIFY_STATUS_SHZ = 101902;
    /**
     * 审核通过
     */
    public static final int VERIFY_STATUS_SHTG = 101903;
    /**
     * 审核未通过
     */

    public static final int VERIFY_STATUS_SHWTG = 101904;
    /**
     * 工作日默认周开始，周一
     */
    public static final String DAYWORK_MIN = "daywork.min";
    /**
     * 工作日默认周结束 周六
     */
    public static final String DAYWORK_MAX = "daywork.max";
    /**
     * 支付状态 未支付
     */
    public static final int NO_PAY = 101601;
    /**
     * 支付状态 支付成功
     */
    public static final int PAY_SUCCESS = 101602;
    /**
     * 支付状态 支付失败
     */
    public static final int PAY_FAIL = 101603;
    /**
     * 订单类型 普通订单
     */
    public static final int NORMAL_ORDER = 103301;
    /**
     * 订单类型 退款维权订单
     */
    public static final int RIGHTS_ORDER = 103302;
    /**
     * 商品订单关联状态 买家申请退款 卖家同意退款 卖家拒绝退款
     */
    public static final int REFUND_STATUS_APPLY = 103401;
    public static final int REFUND_STATUS_AGREE = 103402;
    public static final int REFUND_STATUS_REFUSE = 103403;
    /**
     * 订单的状态 待发货 待收货 已完成 付款
     */
    public static final int ORDER_WAIT = 103501;
    public static final int ORDER_RECEIVE = 103502;
    public static final int ORDER_FINISH = 103503;
    public static final int ORDER_WAIT_PAY = 103504;
    public static final int ORDER_CANCLE = 103505;
    public static final int ORDER_REFUNDDING = 103506;
    public static final int ORDER_CLOSE = 103507;
    public static final int ORDER_WAIT_EVALUEATE = 103508;

}
